<template>
  <div class="padding-16">
    <a-card class="general-card" title="字典管理">
      <a-form
        ref="refSearchForm"
        :model="searchForm"
        auto-label-width
      >
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item field="name" label="字典名称">
              <a-input v-model="searchForm.name" placeholder="请输入字典名称" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="code" label="字典编码">
              <a-input v-model="searchForm.code" placeholder="请输入字典编码" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="status" label="状态">
              <a-select v-model="searchForm.status" :options="statusOptions" placeholder="全部" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-space :size="16">
              <a-button type="primary" @click="handleSearch(1)">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="$refs.refSearchForm.resetFields()">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-divider style="margin-top: 0" />
      <a-space style="margin-bottom: 16px">
        <a-button size="small" type="primary" @click="handleEdit({})">
          <template #icon>
            <icon-plus />
          </template>
          新增
        </a-button>
      </a-space>
      <a-table
        bordered
        row-key="id"
        :data="tableData"
        :loading="pageLoading"
        :pagination="pageData"
        :on-page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="ID" data-index="id"></a-table-column>
          <a-table-column title="字典名称" data-index="name"></a-table-column>
          <a-table-column title="字典编码" data-index="code"></a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <DictBadge :options="statusOptions" :value="record.status"/>
            </template>
          </a-table-column>
          <a-table-column title="备注" data-index="remark"></a-table-column>
          <a-table-column title="创建时间" data-index="create_time"></a-table-column>
          <a-table-column title="操作" :width="160">
            <template #cell="{ record }">
              <!--              <a-button type="text" @click="$router.push({name: 'SystemDictData', query: {id: record.id}})">-->
              <!--                数据管理-->
              <!--              </a-button>-->
              <a-button type="text" @click="handleOpenDetail(record)">
                数据管理
              </a-button>
              <a-button type="text" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button v-if="record.id !== 10000" type="text" status="danger">删除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增 & 编辑 弹窗 -->
    <a-modal
      v-model:visible="dialogVisible"
      width="680px"
      :title="`${formState.id ? '编辑' : '创建'}字典`"
      :footer="false">
      <a-form
        ref="formRef"
        auto-label-width
        :model="formState"
        :rules="formRules"
        @submit="handleSubmit"
      >
        <a-form-item label="字典名称" field="name">
          <a-input v-model="formState.name" placeholder="请输入字典名称"></a-input>
        </a-form-item>
        <a-form-item label="字典编码" field="code">
          <a-input v-model="formState.code" placeholder="请输入字典编码"></a-input>
        </a-form-item>

        <a-form-item label="状态" field="status">
          <a-radio-group v-model="formState.status">
            <a-radio v-for="item in statusOptions" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formState.remark"
            placeholder="简介"
            auto-size
            :maxlength="200"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <div class="form-footer">
          <a-button type="primary" key="submit" html-type="submit" :loading="pageLoading">确 定</a-button>
          <a-button class="ml-24" @click="handleCancel">取 消</a-button>
        </div>
      </a-form>
    </a-modal>

    <!--  数据管理弹窗  -->
    <ModalData ref="refModalData" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import get from "lodash/get";
import { addDict, delDict, getDictList, updateDict } from "@/api/system/dict";
import { statusOptions } from "@/enums/status";
import ModalData from "@/views/system/dict/modal-data.vue";

export default defineComponent({
  components: { ModalData },
  data() {
    return {
      pageLoading: false,
      statusOptions,
      columns: [

        {
          title: "备注",
          dataIndex: "remark"
        },
        {
          title: "创建时间",
          dataIndex: "create_time"
        },
        {
          title: "操作",
          slotName: "operations",
          width: 240
        }
      ],
      tableData: [],
      // 搜索表单
      pageData: {
        pageSize: 50,
        current: 1,
        total: 0
      },
      searchForm: {
        name: "",
        code: "",
        status: ""
      },
      // 部门树选择
      departOptions: [],
      fieldNames: {
        title: "name",
        key: "id",
        children: "children"
      },
      // 创建弹窗
      dialogVisible: false,
      formState: {
        id: undefined,
        name: undefined,
        code: undefined,
        remark: undefined,
        status: 1
      },
      formRules: {
        name: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        code: [{ required: true, message: "字典编码不能为空", trigger: "change" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.fetchTableData();
  },
  methods: {
    onPageChange(current: number) {
      this.fetchTableData({ current });
    },
    async fetchTableData(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          ...this.pageData
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const { data } = await getDictList(params);

        this.tableData = get(data, "list", []);
        this.pageData.current = data.current || 0;
        this.pageData.total = data.total || 0;
      } catch (err) {
        console.warn(err);
        // Message.error("出了点小问题，请稍后重试！");
      }
      this.pageLoading = false;
    },
    handleSearch(current: number) {
      this.fetchTableData({ current });
    },
    // 打开管理弹窗
    handleOpenDetail(record) {
      if (record.id && this.$refs.refModalData) {
        this.$refs.refModalData.handleOpen(record);
      }
    },
    // 操作
    handleDelete(rowData) {
      if (!rowData.id) return;

      delDict(rowData).then(res => {
        const { code, msg } = res;

        if (code === 200) {
          this.$message.success(msg || "删除成功！");
          this.fetchTableData();
        } else {
          this.$message.error(msg || "出了点小问题，请稍后重试！");
        }
      });
    },
    // 创建表单
    handleEdit(rowData: any) {
      this.dialogVisible = true;
      if (rowData.id) {
        this.formState = {
          id: rowData.id || undefined,
          name: rowData.name || undefined,
          code: rowData.code || undefined,
          remark: rowData.remark || undefined,
          status: rowData.status || 1
        };
      }
    },
    handleCancel() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.dialogVisible = false;
      this.formState = {
        id: undefined,
        name: undefined,
        code: undefined,
        remark: undefined,
        status: 1
      };
    },
    async handleSubmit({ values, errors }) {
      console.log("values:", values, "\nerrors:", errors);
      if (!errors) {
        const params = {
          ...this.formState
        };

        this.pageLoading = true;
        let result = {};
        if (params.id) {
          result = await updateDict(params);
        } else {
          result = await addDict(params);
        }
        const { data, code, msg } = result;

        if (code === 200) {
          this.$message.success(msg || "创建成功！");
          await this.fetchTableData();
          this.handleCancel();
        }
        this.pageLoading = false;
      }
    }
  }
});
</script>


<style scoped lang="less">
.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
